package myDaos;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import model.entities.ControlTableDistInfo;
import model.entities.DirListUpdated;

@Stateless
public class ControlDistDao {
	@PersistenceContext(unitName = "UnileverProcedure")
    private EntityManager em;
	
	public EntityManager getEntityManager() {
        return em;
    }
	
	
	public List<ControlTableDistInfo> getControlDistInfoList(){
		List<ControlTableDistInfo> clist=null;
		try {
			StringBuffer queryBiffer = new StringBuffer();
			queryBiffer.append("SELECT c FROM ControlTableDistInfo c"); 	
			Query q = getEntityManager().createQuery(queryBiffer.toString());
			    clist = q.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return clist;
	}
	
	public List<ControlTableDistInfo> getControlDistInfoList(List<String> interfaceName ,List<String> distributor,Date from,Date to){
		List<ControlTableDistInfo> clist=null;
		try {
			StringBuffer queryBiffer = new StringBuffer();
			queryBiffer.append(" SELECT c FROM ControlTableDistInfo c WHERE 1=1 "); 
		    	
			
			if(interfaceName!=null)
    	    {
				queryBiffer.append(" AND c.interfacenme IN :interfaceName") ;	
    	    }
			
			
			if(distributor!=null)
    	    {
				queryBiffer.append(" AND c.distributorid IN :distributor") ;	
    	    }

			if(from!=null)
    	    {
				queryBiffer.append("  AND trunc(c.createddate) >= trunc(:fDate)") ;	
    	    }

			if(to!=null)
    	    {
				queryBiffer.append("  AND trunc(c.createddate) <= trunc(:tDate)") ;	
    	    }
			
			if(from == null )
    	    {
				queryBiffer.append("  AND trunc(c.createddate) >= trunc(sysdate)-30") ;	
    	    }
				
			
			
			System.out.println(queryBiffer.toString());
			
			Query q = getEntityManager().createQuery(queryBiffer.toString());
 
			if(from!=null){q.setParameter("fDate", from);}
			if(to!=null){q.setParameter("tDate", to);}
			if(distributor!=null ){q.setParameter("distributor", distributor);}
			if(interfaceName!=null){q.setParameter("interfaceName", interfaceName);}
			
			
			clist = q.getResultList();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return clist;
	}
}
